<template>
  <div class="PostArticle">
    <div class="head">
      <el-page-header @back="goBack">
      </el-page-header>
      <p style="text-align: center;font-weight: bolder;margin: 0;">{{ title }}文章页面</p>
    </div>
    <div class="main-body">
      <div class="left-contain">
        <el-card>
          <el-form :rules="rules" ref="form" :model="form" class="demo-form-inline">
            <el-form-item label="标题" prop="title">
              <el-input size="small" type="textarea"  autosize :rows="3" show-word-limit v-model="form.title"
                placeholder="输入标题"></el-input>
            </el-form-item>
            <el-form-item label="文章类型" prop="categoryID">
              <el-select size="small" v-model="form.category_name" placeholder="文章类型">
                <el-option v-for="item in categoryList" :label=item.category_name :value=item.category_name></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <p style="margin: 0;">{{ title }}文章封面</p>
              <el-upload class="avatar-uploader" action="#" :http-request="uploadRequest" :show-file-list="false"
                :before-upload="beforeAvatarUpload">
                <img v-if="form.picture" :src="form.picture" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card style="margin-top: 10px;display: flex;justify-content: center;align-items:center;">
          <el-button size="small" type="primary" style="margin-left: 10px;" @click="reSet">重置内容</el-button>
          <el-button size="small" v-if="title == '发布'" type="primary" @click="saveArticleText(null)">保存草稿</el-button>
          <el-button style="margin-top: 10px;" size="small" type="success" @click="PostArticle">确认{{ title
            }}</el-button>
                      <el-button style="margin-top: 10px;" size="small" type="success" @click="goBack">取消{{ title
            }}</el-button>
            
        </el-card>
      </div>
      <div class="right-contain">
        <el-card>
          <el-form :model="form" :rules="rules1" ref="form1">
            <el-form-item prop="content">
              <el-input type="textarea" placeholder="请输入内容" v-model="form.content" maxlength="10000" show-word-limit>
              </el-input>
            </el-form-item>
          </el-form>

        </el-card>
      </div>
    </div>

  </div>
</template>

<script>
import { getCategoryDetailAPI, getArticleDetailAPI } from '@/api/public'
import { addMyArticleAPI,updateMyArticleAPI } from '@/api/myArticle'
import { upload } from '@/api/web'
export default {
  data() {
    return {
      title: '上传',
      form: {
        id: '',
        title: '',
        content: '',
        categoryID: '',
        category_name: '',
        picture: '',
      },
      categoryList: [],
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ],
        category_name: [
          { required: true, message: '类型不能为空', trigger: 'blur' }
        ],
      },
      rules1: {
        content: [
          { required: true, message: '内容不能为空', trigger: 'blur' }
        ]
      },
    }
  },
  mounted() {
    this.getCategoryList()
  },
  methods: {
    // 上传文件
    async uploadRequest(data) {
      const file = data.file
      // 处理formData类型参数
      const formData = new FormData()
      formData.append('file', file)
      const res = await upload(formData)
      if (res.code === '200') {
        this.$message.success("上传成功")
        this.form.picture = res.data
      } else {
        this.$message.error("上传失败")
      }
    },
    // 上传文件前检查
    beforeAvatarUpload(file) {
      const isJPGandPNG = (file.type === 'image/jpeg') || (file.type === 'image/png');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGandPNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPGandPNG && isLt2M;
    },
    // 表单校验
    formValid() {
      return Promise.all([
        this.$refs.form.validate(),
        this.$refs.form1.validate()
      ]).then(() => {
        return true;
      }).catch(() => {
        return false; // 如果验证失败，则返回 false
      });
    },
    // 发布文章
    PostArticle() {
      this.formValid().then(async (ok) => {
        if (ok) {
          this.form.categoryID = (this.categoryList.find(item => item.category_name == this.form.category_name)).id
          let res = ''
          if (this.form.id) {
            // 修改
            res = await updateMyArticleAPI(this.form)
          } else {
            // 发布
            res = await addMyArticleAPI(this.form)
          }
          if (res.code == 200) {
            this.$message.success(this.title + "成功！")
            localStorage.removeItem('article')
            this.goBack()
            this.reSet()
          } else {
            this.$message.error(res.msg)
          }
        }
      })
    },
    // 保存草稿
    saveArticleText(callback) {
      if (this.$route.query.articleId) {
        if (typeof callback === 'function') {
          callback();
        }
      } else {
        const newForm = localStorage.getItem('article') ? JSON.parse(localStorage.getItem('article')) : null;

        const isFormEmpty = this.isFormEmpty(newForm);
        const isFormDifferent = this.isFormDifferent(newForm);

        if (isFormEmpty || isFormDifferent) {
          this.$confirm("你确定要保存修改吗？").then(() => {
            localStorage.setItem('article', JSON.stringify(this.form));
            if (typeof callback === 'function') {
              callback();
            }
          }).catch(() => {
            // 取消保存时的处理
            if (typeof callback === 'function') {
              callback();
            }
          });
        } else {
          if (typeof callback === 'function') {
            callback();
          }
        }
      }

    },
    // 保存草稿、不为空，并且没有保存记录
    isFormEmpty(newForm) {
      return (
        newForm === null &&
        (
          this.form.title !== '' ||
          this.form.content !== '' ||
          this.form.categoryID !== '' ||
          this.form.picture !== ''
        )
      );
    },
    // 保存草稿、有保存记录，但是记录不一样
    isFormDifferent(newForm) {
      return (
        newForm !== null &&
        (
          newForm.title !== this.form.title ||
          newForm.content !== this.form.content ||
          newForm.categoryID !== this.form.categoryID ||
          newForm.picture !== this.form.picture
        )
      );
    },
    // 重置内容
    reSet() {
      this.form.id = '',
        this.form.title = '',
        this.form.content = '',
        this.form.categoryID = '',
        this.form.picture = '',
        this.$refs.form.clearValidate()
      this.$refs.form1.clearValidate()
    },
    //获取文章类型列表、填充草稿、填充编辑文章内容
    async getCategoryList() {
      const res = await getCategoryDetailAPI()
      this.categoryList = res.data.rows

      // 填充草稿
      if (localStorage.getItem('article')) {
        const newForm = JSON.parse(localStorage.getItem('article'))
        this.form.title = newForm.title
        this.form.content = newForm.content
        this.form.categoryID = newForm.categoryID
        this.form.picture = newForm.picture
      }
      // 填充编辑文章内容
      if (this.$route.query.articleId) {
        this.form.id = this.$route.query.articleId
        this.title = "编辑"
        const res = await getArticleDetailAPI(this.form.id)
        this.form.title = res.data[0].title,
          this.form.content = res.data[0].content
        this.form.category_name = res.data[0].category_name
        this.form.categoryID = (this.categoryList.find(item => item.category_name == this.form.category_name)).id
        this.form.picture = res.data[0].picture
      }
    },
    // 返回键
    goBack() {
      // this.reSet()
      // this.$router.back() ? this.$router.back():this.$router.push('/')
      if (this.form.id) {
        this.reSet()
        this.$router.back()
      } else {
        this.reSet()
        this.$router.push('/')
      }
    },
  },
  // 在用户离开页面前保存表单数据到本地存储
  beforeRouteLeave(to, from, next) {
    this.saveArticleText(() => {
      next();
    });
  }
}
</script>

<style>
.PostArticle {
  .head {
    margin: 20px;
  }

  .main-body {
    display: flex;
  }


  .el-form-item {
    margin-bottom: 0px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }

  .el-card__body,
  .el-main {
    padding: 10px;
  }

  .left-contain {
    width: 20%;
    margin-right: 10px;
  }

  .right-contain {
    width: 80%;

    .el-card {
      height: 480px;
      overflow-y: auto;
    }

    .el-textarea__inner {
      min-height: 460px !important;
      overflow-y: auto;
    }
  }

}
</style>
